package com.dt.lucene;

import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class SearchText {

	public static void main(String[] args) {
		try {
			String indexDir = "D:\\\\data\\\\Lucene\\\\textIndex";
			String field = "content";
			// String keyword = "indexed";
			// String keyword = "Welcome";
			// String keyword = "symon";
			String keyword = "Welcome to Indexed world. It's very interesting:1";

			// 1、打开存储目录，这里使用的是文本系统存储的，对应内存存储：RAMDirectory
			Directory dir = FSDirectory.open(Paths.get(indexDir));

			// 2、构建检索X写入器
			IndexReader indexReader = DirectoryReader.open(dir);
			
			IndexSearcher searcher = new IndexSearcher(indexReader);

			// 3、索引配置信息
			IndexWriterConfig conf = new IndexWriterConfig(new StandardAnalyzer());

			// 4、构建索引器
			IndexWriter indexWriter = new IndexWriter(dir, conf);

			// 3、使用标准通用的分析器，如果要对处理中文，请使用IK、庖丁，否则分词不准确
			Analyzer analyzer = new StandardAnalyzer();

			// 4、构建查询器
			QueryParser parser = new QueryParser(field, analyzer);
			Query query = parser.parse(keyword);

			// 5、根据关键词搜索2条文档的id
			TopDocs topDocs = searcher.search(query, 100);
			for (ScoreDoc scoreDoc : topDocs.scoreDocs) {
				// 根据文档id获取文档
				int docid = scoreDoc.doc;
				Document doc = searcher.doc(docid);
				System.out.println(docid + ":" + "result text: " + doc.get(field) + ", score: " + scoreDoc.score);
			}
			indexWriter.commit();
			indexWriter.close();
			// 6、释放资源
			indexReader.close();
			dir.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}